package com.material.controller;


import com.material.common.config.RuoYiConfig;
import com.material.common.config.ServerConfig;
import com.material.common.entity.ResultResponse;
import com.material.common.utils.DateUtils;
import com.material.common.utils.OssClientUtil;
import com.material.common.utils.file.FileUtils;
import com.material.response.UploadResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Api(tags = "文件上传")
@RestController
@RequestMapping("/file/upload")
public class FileUploadController {


    private static Logger logger = LoggerFactory.getLogger(FileUploadController.class);


    @Autowired
    private ServerConfig serverConfig;

    private static final String BASE_URL = "http://192.168.3.125/files";

    private List<String> imageMimeTypes = Arrays.asList(
            "image/jpeg", "image/png", "image/gif", "image/bmp", "image/tiff"
    );


    private List<String> imageFileExtensions = Arrays.asList(
            "jpg", "jpeg", "png", "gif", "bmp", "tiff"
    );




    @ApiOperation("文件上传")
    @PostMapping("/upload1")
    public ResultResponse upload1(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResultResponse.error("文件为空，请选择文件");
        }
        // 上传文件路径
        String basePath = RuoYiConfig.getUploadPath();
        String datePath = DateUtils.datePath();
        String filePath = basePath + "/" + datePath;
        // 上传并返回新文件名称
        try {
            //String fileName = FileUploadUtils.upload(filePath, file);
            //String url = serverConfig.getUrl() + fileName;
            FileUtils.mkdir(filePath);
            String fileName = file.getOriginalFilename();
            String fileExtension = getFileExtension(fileName);
            fileName = DateUtils.dateTimeNow() + "." +fileExtension;
            String saveFileName = filePath + File.separator + fileName;
            File destFile = new File(saveFileName);

            file.transferTo(destFile);
            String url = BASE_URL + "/" + datePath +"/"+ fileName;

            UploadResponse response = new UploadResponse();
            response.setUrl(url);
            response.setFileName(fileName);
            response.setNewFileName(FileUtils.getName(fileName));
            response.setOriginalFilename(file.getOriginalFilename());
            return ResultResponse.success(response);
        } catch (IOException e) {
            logger.error("上传失败",e);
            return ResultResponse.error("文件上传失败");
        }
    }

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public ResultResponse upload(@RequestParam("file") MultipartFile file){
        if (file.isEmpty()) {
            return ResultResponse.error("文件为空，请选择文件");
        }
        // 上传并返回新文件名称
        try {
            String datePath = DateUtils.datePath();
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            String fileName = datePath + "/" + DateUtils.dateTimeNow() + "." +fileExtension;
            String url = null;
            boolean image = isImage(file);
            if(image){
                url = OssClientUtil.uploadImage(fileName, file.getInputStream());
            }else{
                url = OssClientUtil.uploadFile(fileName, file.getInputStream());
            }

            UploadResponse response = new UploadResponse();
            response.setUrl(url);
            response.setFileName(fileName);
            response.setOriginalFilename(file.getOriginalFilename());
            return ResultResponse.success(response);
        } catch (IOException e) {
            logger.error("上传失败",e);
            return ResultResponse.error("文件上传失败");
        }
    }

    private boolean isImage(MultipartFile file){
        // 获取文件的 MIME 类型
        String contentType = file.getContentType();
        // 获取文件的扩展名
        String fileExtension = getFileExtension(file.getOriginalFilename());
        // 判断文件是否为图片
        if (imageMimeTypes.contains(contentType) && imageFileExtensions.contains(fileExtension)) {
            return true;
        } else {
            return false;
        }
    }

    private  String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }

        // 获取文件名中最后一个点（.）的位置
        int lastIndexOfDot = fileName.lastIndexOf('.');

        // 如果没有点，或者点在文件名的开头（隐藏文件），则没有扩展名
        if (lastIndexOfDot == -1 || lastIndexOfDot == 0) {
            return "";
        }

        // 返回点后面的字符串作为扩展名
        return fileName.substring(lastIndexOfDot + 1);
    }
}
